#include "config.h"
#include "debug.h"
#include "state.h"


#if 0
// smithre5: Detecting studs via Hall sensor was prone to issues. It worked
//           just well enough for a time, but it would always succumb to
//           strange issues. Might have been magnetizing the sensor with the
//           physical design we had. Will keep this code here for now.

class hall_sensor_state : public glove::state
{
public:
   hall_sensor_state(int ip)
      : input_pin(ip),
        calibration_level(0)
   {
   }


   virtual void on_enter()
   {
      DEBUG_PRINTLN("hall_sensor_state: entering hall-sensor");

      pinMode(status_green_pin, OUTPUT);
      pinMode(status_red_pin, OUTPUT);
      pinMode(speaker_pin, OUTPUT);
      digitalWrite(status_green_pin, LOW);
      digitalWrite(status_red_pin, LOW);
      noTone(speaker_pin);

      int32_t calibration_sample_avg = 0;

      digitalWrite(status_red_pin, HIGH);
      delay(calibration_delay);
      digitalWrite(status_red_pin, LOW);

      digitalWrite(status_green_pin, HIGH);
      for (int16_t i = 0; i < calibration_sample_size; ++i) {
         calibration_sample_avg += analogRead(input_pin);
      }
      digitalWrite(status_green_pin, LOW);

      calibration_sample_avg /= calibration_sample_size;
      calibration_level = calibration_sample_avg;

      DEBUG_PRINT("hall_sensor_state: calibration_level = ");
      DEBUG_PRINTDEC(calibration_level);
      DEBUG_PRINTLN();
   }


   virtual void on_update()
   {
      int16_t sensor_level = analogRead(input_pin);

      DEBUG_PRINT("hall_sensor_state: sensor = ");
      DEBUG_PRINTDEC(sensor_level);
      DEBUG_PRINT(",  calibration = ");
      DEBUG_PRINTDEC(calibration_level);
      DEBUG_PRINT(",  threshold = ");
      DEBUG_PRINTDEC(sensor_range_threshold);
      DEBUG_PRINTLN();

      if ((sensor_level - calibration_level) > sensor_range_threshold) {
         digitalWrite(status_green_pin, HIGH);
         tone(speaker_pin, speaker_freq, speaker_time);
      }
      else {
         digitalWrite(status_green_pin, LOW);
      }
   }


   virtual void on_leave()
   {
      digitalWrite(status_green_pin, LOW);
      digitalWrite(status_red_pin, LOW);
      noTone(speaker_pin);

      DEBUG_PRINTLN("hall_sensor_state: leaving hall-sensor");
   }


private:
   const int input_pin;

   static const int16_t speaker_freq = 2200;
   static const int16_t speaker_time = 100;

   static const int16_t sensor_range_threshold = 10;
   static const int16_t calibration_delay = 5000;
   static const int16_t calibration_sample_size = 1000;
   int16_t calibration_level;
};
#endif

